var lib = {
	path : require('path'),
	cp : require('child_process'),
	fs : require('fs'),
	lineReader : require('line-reader'),
	sqlite3 : require('sqlite3').verbose(),
	xlsx : require('node-xlsx'),
	domain : require('domain')
};
var proj = {
	root : lib.path.dirname(process.execPath), //项目文件根目录
	dbf : lib.path.join(lib.path.dirname(process.execPath), 'data.db'),
	db : function(){
		if(!window['sqlite3DB']) {
			window['sqlite3DB'] = new lib.sqlite3.Database(this.dbf);
			window['sqlite3DB'].exec('PRAGMA synchronous = OFF;');
			window['sqlite3DB'].exec('PRAGMA auto_vacuum = 0;');
			window['sqlite3DB'].exec('PRAGMA temp_store = MEMORY;');
			window['sqlite3DB'].exec('PRAGMA cache_size = 4000;');
		}
		return window['sqlite3DB'];
	}, //数据库
	grab : lib.path.join(lib.path.dirname(process.execPath), 'grap', 'grap.exe'),
	cmf : lib.path.join(lib.path.dirname(process.execPath), '全部消息记录.txt'), //当前数据库对应的记录文件
	newCmf : function() {return lib.path.join(proj.root,'全部消息记录-' + new Date().getTime() + '.txt');}//变更消息文件名称
};
$.extend({
	autoExportFile : function () {//自动导出
		//检查全部消息记录.txt是否存在，如果存在则进行备份。
		lib.fs.exists(proj.cmf,function(result) {
			if(result) {lib.fs.rename(proj.cmf,proj.newCmf());};
			
			$.clearTable();
			
			lib.cp.exec(proj.grab,function() {
				//循环遍历检查file的大小与更新时间，如果保持不变，则已经导出完成。就可以进行解析工作。
				var loadi = layer.load('等待QQ导出消息文件，时间较长，请耐心等待...');
				//layer.msg('等待QQ导出消息文件，时间较长，请耐心等待...', 60, 16);
				
				setTimeout(function() {
					$.checkMsg(function(stats) {
						layer.close(loadi);
						$.doImport(proj.cmf,$.refreshGUI);
					});
				}
				,5000);
			});
		});
	},
	refreshGUI : function() {
		$.getMessage(1,20); 
		$.loadQunList();
	},
	checkMsg : function(finished, unfinished ,size ,mtime , i) {
		var stats = lib.fs.statSync(proj.cmf);
		i = (i ? i : 0);
		size && mtime && stats.size == size && stats.mtime.getTime() == mtime.getTime() ? i++ : i = 0;//检查3次，如果3次都一致，则表示文件处理已经完成。
		
		if(i >= 4) finished(stats); else {
			if(unfinished) unfinished(stats);
			setTimeout(function() {
				$.checkMsg(finished, unfinished, stats.size, stats.mtime, i);
			},500);
		}
	},
	checkDB : function(finished, unfinished ,size ,mtime , i) {
		var stats = lib.fs.statSync(proj.dbf);
		i = (i ? i : 0);
		size && mtime && stats.size == size && stats.mtime.getTime() == mtime.getTime() ? i++ : i = 0;//检查3次，如果3次都一致，则表示文件处理已经完成。
		
		if(i >= 4) finished(stats); else {
			if(unfinished) unfinished(stats);
			setTimeout(function() {
				$.checkDB(finished, unfinished, stats.size, stats.mtime, i);
			},500);
		}
	},
	importFile : function() {
		var chooser = $('#file');
	    chooser.unbind().change(function(evt) {
	    	console.log($('#file').val());
	    	if($('#file').val() == '') return;//bug fix;
	    	$.clearTable(function() {
	    		$.doImport($('#file').val().split(';'),function(){$.refreshGUI();});
	    	});
	    });
	    chooser.trigger('click');
	},
	doImport : function (files,callback) {
		var loadi = layer.load('读取消息文件并解析中，时间较长，请耐心等待...');
		$.parseFile(files,function() {
    		$.checkDB(function() {
    			if(callback) callback();
    			layer.close(loadi);
    		});
    	});
	} ,
	process : function(min,max,callback) {
		callback(min,max);
		if( min <= max) {
			setTimeout(function() {
				$.process(++min, max, callback);
			}, 800);
		}
	},
	createTable : function(callback) {
		var db = proj.db();
		db.serialize(function() {
			db.run("CREATE TABLE IF NOT EXISTS QQ_MESSAGE (" +
					"ID INTEGER PRIMARY KEY," +
					"MESSAGE TEXT," +
					"QQ_ID VARCHAR2(255)," +
					"QQ_NAME VARCHAR2(255)," +
					"QUN_ID VARCHAR2(255)," +
					"QUN_NAME VARCHAR2(255)," +
					"INTIME DATETIME" +
					")");// QQ消息
			db.run("CREATE TABLE IF NOT EXISTS QUN (" +
					"ID INTEGER PRIMARY KEY," +
					"QUN_ID VARCHAR2(255)," +
					"QUN_NAME VARCHAR2(255)" +
					")");// QQ群信息
			db.run("CREATE TABLE IF NOT EXISTS QUN_DETAIL (" +
					"ID INTEGER PRIMARY KEY," +
					"QUN_ID VARCHAR2(255)," +
					"QUN_NAME VARCHAR2(255)," +
					"QQ_ID VARCHAR2(255)," +
					"QQ_NAME VARCHAR2(255)" +
					")");// QQ群成员列表
			db.run("CREATE INDEX IF NOT EXISTS IX_QQ_MESSAGE_1 ON QQ_MESSAGE(INTIME)");
		});
		if(callback) setTimeout(callback,500);
	},
	parseFile : function(files,callback) {
		$.createTable(function() {
			var db = proj.db();
			
			var flag = true;
			
			db.serialize(function() {
				try {
					db.exec('BEGIN;');
					$.each(files,function(i,file) {
						var stmt = db.prepare("INSERT INTO QQ_MESSAGE(MESSAGE,QQ_ID,QQ_NAME,QUN_ID,QUN_NAME,INTIME) VALUES (?,?,?,?,?,?)");
						var qunName = '';
						var qqId = '';
						var qqName = '';
						var index = 0;
						var inTime = '';
						var message = '';
						var lineNum = 0;
						lib.lineReader.eachLine(file, function(line, last, cb) {
							lineNum ++;
							if(lineNum == 1 && line.indexOf('消息记录（此消息记录为文本格式，不支持重新导入）') == -1) {
								cb(false);
								if(callback) callback();
								alert('该文件格式不对，请选择从QQ消息管理器中导出的文件！');
								return;
							}
							
							if(line.indexOf('================================================================') == 0) {
								index = 0;
							} else if(line.indexOf('消息对象:') == 0 && index == 1) {//群名称
								qunName = $.trim(line.substr('消息对象:'.length));
							} else if(line.indexOf('消息分组:') == 0 && index == 1) {//群所在分组
								
							} else if(/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}|\d):(\d{2}):(\d{2})$/.test($.trim(line.substr(0,19))) 
									&& line.indexOf('(') > -1 && line.indexOf(')') > -1) {//真正的消息发送者
								message = $.trim(message);
								if(message != '' && message != '[表情]' 
									&& message != '[图片]' && message.indexOf('消息记录（此消息记录为文本格式，不支持重新导入）') == -1) 
									stmt.run(message,qqId,qqName,'',qunName,inTime);
								qqId = line.substring(line.indexOf('(') + 1, line.indexOf(')'));
								qqName = $.trim(line.substring(19, line.indexOf('(')));
								inTime = $.trim(line.substr(0,19));
								message = '';
							} else {
								message = message + (message == '' ? line : '\r\n' + line);
							}
							
							index ++;
							
							if(last) {
								stmt.finalize();
								//db.close();
								flag = false;
								if(callback) callback();
							}
							
							console.log(flag);
							
							cb();
						});
					});
					db.exec('COMMIT;');
					console.log(flag);
					db.run("INSERT INTO QUN(QUN_ID,QUN_NAME) SELECT DISTINCT QUN_ID,QUN_NAME FROM QQ_MESSAGE WHERE 1 = 1");
				} catch(err) {
					alert(err);
				};
			});
		});
	},
	clearTable : function(callback) {
		$.createTable(function() {
			var db = proj.db();
			db.serialize(function() {
				//db.exec('PRAGMA synchronous = OFF;');
				//db.exec('BEGIN;');
				db.run("delete from QQ_MESSAGE where 1 = 1;");
				db.run("delete from QUN where 1 = 1;");
				db.run("delete from QUN_DETAIL where 1 = 1;");
				//db.exec('COMMIT;');
				//db.close();
			});
		});
		if(callback) callback();
	},
	getMessage : function(pageNumber, pageSize) {
		var data = new Array();
		
		var cause = $('#searchKey').val() ? " AND MESSAGE LIKE '%" + $('#searchKey').val() + "%' " : "";
		var edate = $('#edate').datebox('getValue');
		var sdate = $('#sdate').datebox('getValue');
		if($.trim(edate) != '')cause += " AND INTIME <= '" + edate + "' ";
		if($.trim(sdate) != '')cause += " AND INTIME >= '" + sdate + "' ";
		if($('#qqId').val() != '')cause += " AND QQ_ID = '" + $('#qqId').val() + "' ";
		
		var qun = $('#qunTree').tree('getSelected');
		cause += (qun&& qun.value != '' ? " AND QUN_NAME='" + qun.value + "' " : "");
		
		var db = proj.db();
		db.serialize(function() {
			var sql = "SELECT MESSAGE,QQ_ID,QQ_NAME,QUN_ID,QUN_NAME,INTIME FROM QQ_MESSAGE WHERE 1 = 1 " + cause + " ORDER BY INTIME DESC LIMIT " + (pageNumber - 1) * pageSize + "," + pageNumber * pageSize;
			db.each(sql, function(err, row) {
		        data.push(row);
		    });
			db.each("SELECT COUNT(*) TOTAL FROM QQ_MESSAGE WHERE 1 = 1" + cause,function(err,row) {
				if(row) {
					var opts = $('#messageList').datagrid('getPager').pagination('options');
					opts.pageSize = pageSize;
					opts.pageNumber = pageNumber;
					
					$('#messageList').datagrid('loadData', {"total":row.TOTAL,"rows":data});
				}
			});
		}); 
	},
	loadQunList : function() {
		var loadi = layer.load('加载群消息列表中，请稍候...');
		
		$.createTable(function() {
			var data = new Array();
			var db = proj.db();
			db.serialize(function() {
				db.each("SELECT QUN_NAME FROM QUN WHERE 1 = 1 ORDER BY QUN_NAME", function(err, row) {
					if(row) data.push({"text": row.QUN_NAME,value:row.QUN_NAME,"iconCls":"icon-qun"});
			    });
				db.run("SELECT 1 FROM QUN WHERE 1=1 LIMIT 0,1",function(err,row) {
					$('#qunTree').tree('loadData',[{"text":"群列表",value:"","iconCls":"icon-folder",children:data}]);
					layer.close(loadi);
				});
			});
		});
	},
	exportXls : function() {
		/*if($.trim($('#searchKey').val()) == '') {
			alert('请输入关键字！');
			return;
		}*/
		
		var cause = $('#searchKey').val() ? " AND MESSAGE LIKE '%" + $('#searchKey').val() + "%' " : "";
		var edate = $('#edate').datebox('getValue');
		var sdate = $('#sdate').datebox('getValue');
		if($.trim(edate) != '')cause += " AND INTIME <= '" + edate + "' ";
		if($.trim(sdate) != '')cause += " AND INTIME >= '" + sdate + "' ";
		if($('#qqId').val() != '')cause += " AND QQ_ID = '" + $('#qqId').val() + "' ";
		
		var qun = $('#qunTree').tree('getSelected');
		cause += (qun && qun.value != '' ? " AND QUN_NAME='" + qun.value + "' " : "");
		
		var data = [[ "时间","QQ群","昵称","消息内容","QQ"/*,"QQ群ID"*/]];
		
		var db = proj.db();
		$.createTable(function() {
			db.serialize(function() {
				db.each("SELECT MESSAGE,QQ_ID,QQ_NAME,QUN_ID,QUN_NAME,INTIME FROM QQ_MESSAGE WHERE 1 = 1 " + cause + " ORDER BY INTIME DESC ", function(err, row) {
			        data.push([row.INTIME,row.QUN_NAME,row.QQ_NAME,row.MESSAGE,row.QQ_ID/*,row.QUN_ID*/]);
			    });
				db.run("SELECT 1 FROM QQ_MESSAGE WHERE 1=1 LIMIT 0,1",function(erro,row) {
					var file = lib.xlsx.build({"worksheets" : [ {"data" : data} ]});
					var _path = new Date().getTime() + '.xls';
					lib.fs.writeFileSync(_path, file, 'binary');
					window.location.href = _path;
				});
			});
		});
	},
	catchError : function(callback) {
		var d = lib.domain.create();
		d.on('error',function(err) {
			console.log(err);
		});
		
		d.run(callback);
	}
});